<template>
    <div id="vditor"></div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import notify from '@/plugins/NotifyPlugin';
import { useEvent } from '@/utils/event/useEvent';
import { EventCenter } from '@/utils/event/eventCenter';
import { getValidToken, tokenAxios } from '@/utils/tokenAxiosUtils';
import { BlogUpload } from '@/types/blogType';

// 定义常量
const EDITOR_WIDTH = '50vw';
const EDITOR_HEIGHT = '90vh';

// 创建一个响应式引用
const contentEditor = ref(null);
const { eventOn } = useEvent();

// 添加一个响应式变量来控制是否可以上传
const canUpload = () => {
    return contentEditor.value.getValue() !== '';
};

// 组件挂载后初始化 Vditor
onMounted(async () => {
    contentEditor.value = new Vditor('vditor', {
        width: EDITOR_WIDTH,
        height: EDITOR_HEIGHT,
        toolbarConfig: { pin: true },
        after: () => {
            contentEditor.value.setValue('hello, Vditor + Vue!');
        },
        upload: {
            url: '/api/blog/uploadFile',
            accept: 'image/*',
            max: 2 * 1024 * 1024,
            multiple: true,
            fieldName: 'files',
            headers: {
                'Authorization': `Bearer ${await getValidToken()}`
            },
            filename(name) {
                return name
                    .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '')
                    .replace(/[\?\\/:|<>\*$$$$$$\$%\{\}@~]/g, '')
                    .replace('/\\s/g', '');
            },
        }
    });
});

eventOn(EventCenter.UploadBlog, (uploadData) => {
    canUpload && uploadData ? uploadBlog(uploadData) : handleEmptyBlog();
})


// 上传博客
const uploadBlog = async (uploadData: { title: string, summary: string, tags: string[] }) => {
    console.log(contentEditor.value.getValue());

    const blogUpload: BlogUpload = {
        title: uploadData.title,
        summary: uploadData.summary,
        tags: uploadData.tags,
        content: contentEditor.value.getValue()
    }

    try {
        const response = await tokenAxios.post('/blog/create', blogUpload);
        console.log(response.data);
        notify('上传成功', '', 'success');
    } catch (error) {
        // 处理上传失败的逻辑
        notify('上传失败', '', 'error');
        console.error('上传博客失败:', error);
    }
};

// 处理博客内容为空的情况
const handleEmptyBlog = () => {
    // 这里可以添加具体的逻辑，比如提示用户博客内容为空
    notify('上传失败', '博客不能为空！', 'error');
};
</script>
